export function setLocalStorage(name: string, value: string) {
  if (window.localStorage) {
    window.localStorage.setItem(name, value)
  }
}

export function getLocalStorage(name: string) {
  if (window.localStorage) {
    const value = window.localStorage.getItem(name)
    return value === null ? '' : value
  }
  return ''
}

export function removeLocalStorage(name: string) {
  if (window.localStorage) {
    window.localStorage.removeItem(name)
  }
}

export function checkArrayIncludes(parent: any, child: any) {
  return child.every((item: any) => parent.includes(item))
}

export function htmlEncode(stringReplace: string) {
  let s = ''
  if (stringReplace.length === 0) {
    return ''
  }
  s = stringReplace.replace(/&/g, '&amp;')
  s = s.replace(/</g, '&lt;')
  s = s.replace(/>/g, '&gt;')
  s = s.replace(/ /g, '&nbsp;')
  s = s.replace(/'/g, '&#39;')
  s = s.replace(/"/g, '&quot;')
  s = s.replace(/\n/g, '<br/>')
  return s
}

// check 目标字符在 string 中出现对次数是否为奇数
export function stringOccurOddTimes(string: string, target: string) {
  const object: any = {}
  // eslint-disable-next-line unicorn/no-for-loop
  for (let i = 0; i < string.length; i += 1) {
    const key = string[i]
    if (object[key]) {
      object[key] += 1
    } else {
      object[key] = 1
    }
  }
  if (object[target]) {
    return object[target] % 2 !== 0
  }
  return false
}

export function htmlDecode(stringReplace: string) {
  let s = ''
  if (stringReplace.length === 0) {
    return ''
  }
  s = stringReplace.replace(/&amp;/g, '&')
  s = s.replace(/&lt;/g, '<')
  s = s.replace(/&gt;/g, '>')
  s = s.replace(/&nbsp;/g, ' ')
  s = s.replace(/&#39;/g, '\'')
  s = s.replace(/&quot;/g, '"')
  s = s.replace(/<br\/>/g, '\n')
  return s
}

// waterMark 绘制与删除
export function deleteWatermark(id: string) {
  if (document.querySelector(`#${id}`) !== null) {
    const node: any = document.querySelector(`#${id}`)
    node.remove()
  }
}
//  存储水印字符串
let waterMarkString = ''
let drawArea = ''
const drawWatermark = () => {
  const id: string = 'water_mark'

  deleteWatermark(id)
  //  创建一个画布
  const can = document.createElement('canvas')
  //  设置画布的长宽，画布密集程度
  can.width = 180
  can.height = 180

  const cans: any = can.getContext('2d')
  //  旋转角度，画布倾斜程度
  cans.rotate((-20 * Math.PI) / 180)
  cans.font = 'normal 14px'
  cans.fontWeight = '500'
  //  设置填充绘画的颜色、渐变或者模式
  cans.fillStyle = '#222432'
  //  设置文本内容的当前对齐方式
  cans.textAlign = 'left'
  //  设置在绘制文本时使用的当前文本基线
  cans.textBaseline = 'Middle'
  //  在画布上绘制填色的文本（输出的文本，开始绘制文本的X坐标位置，开始绘制文本的Y坐标位置）
  cans.fillText(waterMarkString, can.width / 8, can.height / 2)

  const div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.top = '0px'
  div.style.left = '0px'
  div.style.position = 'absolute'
  div.style.zIndex = '1000'
  div.style.opacity = '0.1'
  const area: any = document.querySelector(drawArea) // 作为参数传入
  div.style.width = `${area.clientWidth}px`
  div.style.height = `${area.clientHeight}px`
  div.style.background = `url(${can.toDataURL('image/png')}) left top repeat`
  area.append(div)
  return id
}
export function setWatermark(
  text: string,
  area: string,
  fromPublish: boolean = false
) {
  waterMarkString = fromPublish ? text : `之江天枢_${text}`
  drawArea = area
  drawWatermark()
  window.addEventListener('resize', drawWatermark)
}

export function removeResizeListener() {
  window.removeEventListener('resize', drawWatermark)
}

function isMac() {
  const { userAgent } = window.navigator
  return userAgent.includes('Mac OS X')
}

/**
 * 是否按住ctrl多选模式：win下按住ctrl键，mac下按住command键
 */
export function isCtrlSelect(event: MouseEvent) {
  if (isMac()) {
    return event.metaKey
  }
  return event.ctrlKey
}
/** 重新计算尺寸与坐标裁切画布空白部分 */
export function clipGraphData(
  graphData: any,
  maxWidth: number,
  maxHeight: number,
  minWidth = 400,
  minHeight = 400
) {
  const result = graphData
  /* eslint-disable */
  if (
    graphData.data?.nodes &&
    graphData.data.nodes.__proto__.constructor === Array
  ) {
    const padding = 50
    let maxX = 0
    let maxY = 0
    let minX = 999999999
    let minY = 999999999
    ;(result.data.nodes as Array<any>).forEach((nodeData: any) => {
      maxX = Math.max(maxX, nodeData.x as number)
      minX = Math.min(minX, nodeData.x as number)
      maxY = Math.max(maxY, nodeData.y as number)
      minY = Math.min(minY, nodeData.y as number)
    })
    // 加上padding
    maxX += padding
    maxY += padding
    minX -= padding
    minY -= padding
    // 需要加上title的尺寸
    const sizeCalc = [maxX - minX, maxY - minY + 40]
    /* 超过画布大小以最大画布尺寸为准，（这里暂时不做缩放处理） */
    if (sizeCalc[0] > maxWidth) {
      sizeCalc[0] = maxWidth - 40
    }
    if (sizeCalc[1] > maxHeight) {
      sizeCalc[1] = maxHeight - 40
    }
    /** 低于400 * 400， 按400 * 400展示 */
    if (sizeCalc[0] < minWidth) {
      const offsetX = minWidth - sizeCalc[0]
      minX -= offsetX / 2
      maxX += offsetX / 2
      sizeCalc[0] = minWidth
    }

    if (sizeCalc[1] < minHeight) {
      const offsetY = minHeight - sizeCalc[1]
      minY -= offsetY / 2
      maxY += offsetY / 2
      sizeCalc[1] = minHeight
    }
    result.data.size = sizeCalc
    result.data.nodes = (result.data.nodes as Array<any>).map(
      (nodeData: any) => {
        return {
          ...nodeData,
          x: nodeData.x - minX,
          y: nodeData.y - minY,
        }
      }
    )
  }
  return result
}
/*获取缩放坐标点*/
export function getNewPo(
  po: [number, number],
  center: [number, number],
  scale: number
): [number, number] {
  return [
    (po[0] - center[0]) * scale + center[0],
    (po[1] - center[1]) * scale + center[1],
  ]
}

/** 根据中心点以及缩放比例算出新的坐标信息 */
export function scaleNodes(
  nodes: Array<any>,
  center: [number, number],
  scale: number
) {
  return nodes.map((node) => {
    const pointScale = getNewPo([node.x, node.y], center, scale)
    return {
      ...node,
      x: pointScale[0],
      y: pointScale[1],
    }
  })
}
